package interpreter.practice_02;

import java.util.HashMap;
import java.util.Stack;

/**
 * @author yi qiang
 * @date 2021/6/20 22:05
 */
public class Calculate {

    private AbstractExpression expression;

    /**
     * 将expStr转化成expression
     * @param expStr 表达式字符串
     */
    public Calculate(String expStr){
        Stack<AbstractExpression> stack=new Stack<>();
        char[] charArray=expStr.toCharArray();

        AbstractExpression left;
        AbstractExpression right;
        for(int i=0;i<charArray.length;i++){
            switch (charArray[i]){
                case '+':
                    left=stack.pop();
                    right=new ValExpression(String.valueOf(charArray[++i]));
                    stack.push(new AddExpression(left,right));
                    break;
                case '-':
                    left=stack.pop();
                    right=new ValExpression(String.valueOf(charArray[++i]));
                    stack.push(new SubExpression(left,right));
                    break;
                default:
                    stack.push(new ValExpression(String.valueOf(charArray[i])));
                    break;
            }
        }
        this.expression=stack.pop();
    }

    public int run(HashMap<String,Integer> val){
        return this.expression.interpreter(val);
    }

}
